package org.micode.libs.servlet.utils;

import org.micode.common.consts.HttpHeadConsts;
import org.micode.common.utils.StringExtUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

@Slf4j
public class HttpContextUtils {

    public static final String LOCAL_IP = "127.0.0.1";

    private static final String UN_KNOWN = "unknown";

    public static HttpServletRequest getHttpServletRequest() {
        ServletRequestAttributes servletRequestAttr =
                (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (null == servletRequestAttr) {
            return null;
        }
        return servletRequestAttr.getRequest();
    }

    public static String getIp() {
        return getIp(getHttpServletRequest());
    }

    /**
     * 获取请求ip
     *
     * @param request
     * @return
     */
    public static String getIp(HttpServletRequest request) {
        try {
            String realIp = request.getHeader("X-Real-IP");
            String forwardedIp = request.getHeader("X-Forwarded-For");
            if (!StringUtils.isEmpty(forwardedIp) && !UN_KNOWN.equalsIgnoreCase(forwardedIp)) {
                // 多次反向代理后会有多个ip值，第一个ip才是真实ip
                int index = forwardedIp.indexOf(",");
                if (index != -1) {
                    return forwardedIp.substring(0, index);
                } else {
                    return forwardedIp;
                }
            }
            forwardedIp = realIp;
            if (!StringUtils.isEmpty(forwardedIp) && !UN_KNOWN.equalsIgnoreCase(forwardedIp)) {
                return forwardedIp;
            }

            forwardedIp = readIpForHeader(request, "Proxy-Client-IP", forwardedIp);
            forwardedIp = readIpForHeader(request, "WL-Proxy-Client-IP", forwardedIp);
            forwardedIp = readIpForHeader(request, "HTTP_CLIENT_IP", forwardedIp);
            forwardedIp = readIpForHeader(request, "HTTP_X_FORWARDED_FOR", forwardedIp);

            if (StringUtils.isBlank(forwardedIp) || UN_KNOWN.equalsIgnoreCase(forwardedIp)) {
                forwardedIp = request.getRemoteAddr();
            }

            return forwardedIp;
        } catch (Exception e) {
            return "未获取到IP";
        }
    }

    public static String getDomain(){
        HttpServletRequest request = getHttpServletRequest();
        StringBuffer url = request.getRequestURL();
        return url.delete(url.length() - request.getRequestURI().length(), url.length()).toString();
    }

    public static String getOrigin(){
        HttpServletRequest request = getHttpServletRequest();
        return request.getHeader("Origin");
    }

    /**
     * 获取请求中的token
     *
     * @param request
     * @return
     */
    public static String getToken(HttpServletRequest request) {
        String token = request.getHeader(HttpHeadConsts.REQUEST_HEADER_TOKEN_KEY);
        if (StringUtils.isAnyEmpty(token)) {
            token = request.getHeader(HttpHeadConsts.REQUEST_HEADER_AUTH_KEY);
            if (StringUtils.isAnyEmpty(token)) {
                Map<String, String[]> properties = request.getParameterMap();
                log.trace("httpServletRequest.getParameterMap:{}", StringExtUtils.mapToString(properties));
                if (properties.containsKey(HttpHeadConsts.REQUEST_QUERY_TOKEN_KEY)) {
                    return properties.get(HttpHeadConsts.REQUEST_QUERY_TOKEN_KEY)[0];
                }
            }
        }

        return token;
    }

    private static String readIpForHeader(HttpServletRequest request,
                                          String fieldName, String currentIp) {
        if (StringUtils.isBlank(currentIp) || UN_KNOWN.equalsIgnoreCase(currentIp)) {
            return request.getHeader(fieldName);
        } else {
            return currentIp;
        }
    }

    public static String getClientApp() {
        return getClientApp(getHttpServletRequest());
    }

    public static String getClientApp(HttpServletRequest request) {
        if (null == request) {
            return null;
        }

        String clientApp = request.getHeader(HttpHeadConsts.REQUEST_HEADER_CLIENT_APP_KEY);
        if (StringUtils.isAnyEmpty(clientApp)) {
            clientApp = request.getHeader(HttpHeadConsts.REQUEST_HEADER_CLIENT_APP_KEY1);
            if (StringUtils.isAnyEmpty(clientApp)) {
                Map<String, String[]> properties = request.getParameterMap();
                if (properties.containsKey(HttpHeadConsts.REQUEST_LOGIN_APP)) {
                    return properties.get(HttpHeadConsts.REQUEST_LOGIN_APP)[0];
                }
            }
        }

        return clientApp;
    }

}
